import { Directive, OnInit, ElementRef, Input, OnDestroy } from '@angular/core';

import { BaseView } from '../../core/view/base-view';
import { Subscription } from 'rxjs';

@Directive({
  // tslint:disable-next-line:directive-selector
  selector: 'button,input[type=button],[smooth-click]'
})
export class SmoothClickDirective<U, B, S> extends BaseView<U, B, S> implements OnInit, OnDestroy {

  // tslint:disable-next-line:no-input-rename
  @Input('click-min-interval') intervalTime = 500;
  private lastClickTime = 0;
  private subscription: Subscription;

  constructor(
    private ele: ElementRef) {
    super();
  }

  ngOnInit(): void {
    this.intervalTime = parseInt(this.intervalTime + '', 10);
    if (Number.isNaN(this.intervalTime)) {
      this.loggerService.warn('click-interval must be number', 'SmoothClickDirective');
      return;
    }

    this.subscription = this.broadcastService.subscribe(<any>'GlobalClick', (e) => {
      if (e.target !== this.ele.nativeElement) {
        return;
      }

      const now = Date.now();
      if (this.lastClickTime > 0 && now - this.lastClickTime < this.intervalTime) {
        e.stopImmediatePropagation();
        e.preventDefault();
        this.messageService.warning(this.i18nService.getValue('@djgypf'));
      }

      this.lastClickTime = Date.now();
    });
  }

  ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}
